import { ref, inject } from "vue";
import { useLoginUserStore } from "../../../store";
import { useOrgStore } from '../../../store/useOrgStore'

interface Tree {
    id: string;
    label: string;
    value: string;
    children?: Tree[];
}

export const useOrgTree = () => {
    //获取API配置
    const API = inject("API") as any;
    const ApiConfig = inject("ApiConfig") as any;

    const loginUserStore = useLoginUserStore();
    const orgStore = useOrgStore();

    //默认设置当前用户所在机构id为选中id
    orgStore.setSelectedOrgNode({ 'id': loginUserStore.currentUser.orgId, 'label': loginUserStore.currentUser.orgName });

    const data = ref<Tree[]>([]);

    const fetchData = async () => {
        try {
            const response = await API.request(
                ApiConfig.Methods.GET,
                ApiConfig.PATH.Org.GetAllOrgByOrgId,
                { orgId: orgStore.selectedOrgNode.id, searchAll: orgStore.searchAll }
            );

            if (response.status == "200" && response.data.code == "200") {
                const transformOrgData: any = (orgList: any[]) => {
                    return orgList.map((org) => {
                        return {
                            id: org.id,
                            label: org.orgName,
                            value: org.orgName,
                            children: org.childOrgList
                                ? transformOrgData(org.childOrgList)
                                : [],
                        };
                    });
                };
                data.value = transformOrgData(response.data.data);
            }
        } catch (error) {
            console.error(error);
        }
    };

    return {
        data,
        orgStore,
        fetchData,
    };
};
